const jwt = require('jsonwebtoken')

module.exports = (options, app) => {
    return async function checkToken(ctx, next) {
        if(ctx.url !== '/'){
            let token = ctx.header.authorization;
            if (token) {
                try {
                    await jwt.verify(token, options.jwtKey); //如果 token 过期或验证失败，将返回401
                    await next();
                } catch (err) {
                    ctx.throw(401, 'invalid token')
                }
            } else {
                ctx.throw(401, 'no token detected in http header "Authorization"');
            }
        }else{
            await next();
        }
    }
}